package com.study.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;

public class RedisSortSet {

	public static void main(String[] args) {
		Jedis jedis = RedisUtil.getJedis();
		//向有序集合zset中添加zs和li的成绩和姓名
		
		//jedis.zadd("zset", 99, "zs");
		Map<String, Double> scoreMembers = new HashMap<String,Double>();
		scoreMembers.put("zs", 90.0);
		scoreMembers.put("li", 89.0);
		jedis.zadd("zset", scoreMembers);
		
		//通过索引返回有序集合指定区间的成员
		Set<Tuple> scores = jedis.zrangeWithScores("zset", 0, -1);
		System.out.println("zset的成员：");
		for (Tuple tuple : scores) {
			System.out.println(tuple.getElement());
			System.out.println(tuple.getScore());
		}
		
		//获取有序集合的成员数
		long count = jedis.zcard("zset");
		System.out.println("集合的个数：" + count);
		
		//查询分数在90和100之间的学员个数
		count = jedis.zcount("zset", 90, 100);
		System.out.println("分数在90和100之间的学员个数：" + count);
		
		//返回li在集合中的索引 redis是安装score从小到大排序的，所以li在一位
		long index = jedis.zrank("zset", "li");
		System.out.println("li在集合中的索引:" + index);
		
		//移除学员li
		jedis.zrem("zset", "li");
		
		//根据排名移除集合中的元素
		jedis.zremrangeByRank("zset", 0, 2);
		
		scoreMembers.put("zs", 80.0);
		scoreMembers.put("ls", 90.0);
		scoreMembers.put("ws", 85.0);
		jedis.zadd("zset", scoreMembers);
		
		//根据分数移除集合中的元素
		jedis.zremrangeByScore("zset", 80, 85);
		
		//返回ls的分值
		double score = jedis.zscore("zset", "ls");
		System.out.println("ls的分值：" + score);
		
		jedis.zadd("zset", 95, "zs");
		
		//通过索引，从高到低返回指定区间的元素
		scores = jedis.zrevrangeWithScores("zset", 0, -1);
		for (Tuple tuple : scores) {
			System.out.println(tuple.getElement());
			System.out.println(tuple.getScore());
		}
		//通过分数，从高到低返回指定区间的元素
		scores = jedis.zrevrangeByScoreWithScores("zset", 95, 80);
		for (Tuple tuple : scores) {
			System.out.println(tuple.getElement());
			System.out.println(tuple.getScore());
		}
		//将ls的分数加10
		jedis.zincrby("zset", 10, "li");
		scores = jedis.zrangeWithScores("zset", 0, -1);
		System.out.println("zset的成员：");
		for (Tuple tuple : scores) {
			System.out.println(tuple.getElement());
			System.out.println(tuple.getScore());
		}
		jedis.close();
	}
}
